﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using System.Diagnostics;
using System.IO;
using System.Xml.Linq;
using System.Text;
using Microsoft.Phone.Shell;
using System.Windows.Controls.Primitives;
using System.IO.IsolatedStorage;
using System.Threading;

namespace ByrForum
{
    public partial class TopTen : PhoneApplicationPage
    {
        public bool if_loaded = false;
        public string board = "";
        public string group_id = "";
        public int holdIndex = -1;
        public string replyId = "";
        public string replyUserId = "";
        public string appendText = "";
        public bool waitRender = false;
        int itemNum = 0;
        ApplicationBarIconButton BarButtonFirstPageButton;
        ApplicationBarIconButton BarButtonForward;
        ApplicationBarIconButton BarButtonBackwoard;
        ApplicationBarIconButton BarButtonLastPageButton;
        
       public string titleToDisplay = "";
        public List<ArticleData> listArticle = new List<ArticleData>();
        public int total_page = 1;
        public int current_page = 1;
        public TopTen()
        {
            InitializeComponent();
            Debug.WriteLine("CONSTRUCT FUNCTION");
            BarButtonFirstPageButton = this.ApplicationBar.Buttons[0] as ApplicationBarIconButton;
            BarButtonForward= this.ApplicationBar.Buttons[1] as ApplicationBarIconButton;
            BarButtonBackwoard = this.ApplicationBar.Buttons[2] as ApplicationBarIconButton;
            BarButtonLastPageButton = this.ApplicationBar.Buttons[3] as ApplicationBarIconButton;
            BarButtonForward.IsEnabled = false;
            BarButtonBackwoard.IsEnabled = false;

        }
        public void GetData()
        { 
            
        }

        protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
        {
            if (!if_loaded)
            {
                Debug.WriteLine("ON NAVIGATED TO");
                
                IDictionary<string, string> queryString = this.NavigationContext.QueryString;
                queryString.TryGetValue("group_id", out group_id );
                queryString.TryGetValue("board", out board);
                queryString.TryGetValue("title", out titleToDisplay);
                this.PageTitle.Text = titleToDisplay;
                 string url = ByrApi.apiUrl + "/threads/" + board + "/" +
                  group_id + ByrApi.Encode + ByrApi.appkey;
                 Debug.WriteLine(url);
                base.OnNavigatedTo(e);
                ShowState(0);
                //this.progressBarWait.Visibility = Visibility.Visible;
                HttpUtil.HttpGet(url, HttpWebRequset_Callback);
                
            }
           

        }
        private void HttpWebRequset_Callback(IAsyncResult asynchronousResult)
        {

            listArticle.Clear();
            try
            {
               string result= HttpUtil.ReadToEnd(asynchronousResult);
               DebugInfo.writeXml(result);
                try{
                XDocument doc = XDocument.Parse(result);
                string username="", face_url="", content="",id="",title="",userid="",post_time="";
               // List<string> ls = new List<string>();
               // if (!if_loaded)
                {
                    foreach (XElement item in doc.Descendants("pagination").Nodes())
                    {
                        switch (item.Name.ToString())
                        {
                            case "page_all_count":
                                total_page = Convert.ToInt32(item.Value);
                                Debug.WriteLine("page_all_count:" + total_page);
                                if (total_page != 1)
                                {
                                    this.Dispatcher.BeginInvoke(

                                        () =>
                                        {
                                            this.BarButtonBackwoard.IsEnabled = true;
                                        }
                                        );
                                }
                                break;
                            case "page_current_count":
                                current_page = Convert.ToInt32(item.Value);
                                Debug.WriteLine("page_current_count:" + current_page);
                                
                                break;
                            default:
                                break;
                        }


                    }
                    if (total_page == current_page)
                    {
                        this.Dispatcher.BeginInvoke(
                                () =>
                                {
                                    if (current_page == total_page)
                                    {
                                        BarButtonBackwoard.IsEnabled = false;
                                    }
                                    else
                                        BarButtonBackwoard.IsEnabled = true;
                                    if (current_page != 1)
                                    {
                                        BarButtonForward.IsEnabled = true;
                                    }
                                    else
                                        BarButtonForward.IsEnabled = false;
                                }
                            );
                    }
                }
                
                foreach (XElement item in doc.Descendants("article").Nodes())
                {
                    List<string> ls = new List<string>();
                    if (item.Name == "item")
                    {
                        
                        foreach(XElement user_item in item.Descendants("user").Nodes())
                        {
                            if (user_item.Name == "user_name")
                                {
                                    username = user_item.Value;
                                }
                            if (user_item.Name == "id")
                            {
                                userid = user_item.Value;
                            }
                            if (user_item.Name == "face_url")
                                {
                                    face_url = user_item.Value;
                                    Debug.WriteLine("face_url:"+face_url);
                                }
                        }
                        foreach (XElement article_item in item.Elements())
                        {
                            Debug.WriteLine(article_item.Name);
                            if (article_item.Name == "content")
                            {
                                content = article_item.Value;
                                DebugInfo.writeXml("content:"+content);
                            }
                            if (article_item.Name == "title")
                            {
                                title = article_item.Value;
                                DebugInfo.writeXml("title:" + title);

                            }
                            if (article_item.Name == "id")
                            {
                                id = article_item.Value;
                            }
                            if (article_item.Name == "post_time")
                            {
                                post_time = article_item.Value;
                            }

                            if (article_item.Name == "attachment")
                            {
                                foreach (XElement attachment_item in article_item.Descendants("file").Nodes())
                                {
                                    if (attachment_item.Name == "item")
                                    { 
                                        foreach(XElement att_item in attachment_item.Elements())
                                        {
                                            if (att_item.Name == "thumbnail_middle")
                                            {
                                                ls.Add(att_item.Value);
                                                Debug.WriteLine("attachment url"+att_item.Value);
                                            }
                                        }
                                    }
                                }
                            }
                        }
                        ArticleData ad = new ArticleData(username, face_url, content,id,title,userid,ls,post_time);
                        PassValue pv = new PassValue(ad);
                        ///((Grid)listbox.Items[0]).Children.Add()
                        listArticle.Add(ad);

                        this.Dispatcher.BeginInvoke(
                            () =>
                            {
                                this.listbox.Items.Add(pv);
                                ShowState(1);
                                if (current_page == total_page)
                                {
                                    BarButtonBackwoard.IsEnabled = false;
                                }
                                else
                                    BarButtonBackwoard.IsEnabled = true;
                                if (current_page != 1)
                                {
                                    BarButtonForward.IsEnabled = true;
                                }
                                else
                                    BarButtonForward.IsEnabled = false;
                                // this.progressBarWait.Visibility = Visibility.Collapsed;
                            }
                            );
                        
                    }
                    
                    
                }
                
                }
                catch (Exception e)
                {
                    Debug.WriteLine(e.Message);
                }
            }
            catch
            { }

            if_loaded = true;
        }

        private void ForwardButton_Click(object sender, EventArgs e)
        {
            GoToPage(--current_page);
            if (current_page != total_page)
            {
                BarButtonBackwoard.IsEnabled = true;
            }
            if (current_page == 1)
            {
                BarButtonForward.IsEnabled = false;
            }
        }

        private void BackwardButton_Click(object sender, EventArgs e)
        {
            GoToPage(++current_page);
            if (current_page == total_page)
            {
                BarButtonBackwoard.IsEnabled = false;
            }
            if (current_page !=1 )
            {
                BarButtonForward.IsEnabled = true;
            }
        }
        public bool IsLegalXmlChar(int character)

            {
                return
                (
                    character == 0x9 /* == '\t' == 9   */          ||

                     character == 0xA /* == '\n' == 10  */          ||

                     character == 0xD /* == '\r' == 13  */          ||

                    (character >= 0x20    && character <= 0xD7FF  ) ||

                    (character >= 0xE000  && character <= 0xFFFD  ) ||

                    (character >= 0x10000 && character <= 0x10FFFF)

                );

            }

        private void listbox_Tap(object sender, System.Windows.Input.GestureEventArgs e)
        {
            string[] originText;
            if (!if_loaded ||(listbox.SelectedIndex==-1))
                return;
            appendText = "【在" + listArticle[listbox.SelectedIndex].Userid + "的大作中提到: 】\n";
            originText= listArticle[listbox.SelectedIndex].Content.Split('\n');
            for (int i = 0; i < originText.Length; i++)
            {
                appendText += ": " + originText[i]+"\n";
                if (i > 1) break;
            }
            appendText += ": ...................\n";
            Debug.WriteLine("appendText:"+appendText);
            replyId = listArticle[listbox.SelectedIndex].Id;
            replyUserId = listArticle[listbox.SelectedIndex].Userid;

            ReplyPopup rp = new ReplyPopup(this);
            PopupCotainer pc = new PopupCotainer(this);
            pc.Show(rp);
            

        }

        private void ReplyButton_Click(object sender, EventArgs e)
        {
            replyId = group_id;
            replyUserId = "";
            ReplyPopup rp = new ReplyPopup(this);
            PopupCotainer pc = new PopupCotainer(this);
            pc.Show(rp);
        }

        private void ListItem_Hold(object sender, Microsoft.Phone.Controls.GestureEventArgs e)
        {
            var holdItem = (sender as Grid).DataContext;
            int i = 0;
            foreach (var item in listbox.Items)
            {
                
                if (item == holdItem)
                    break;
                i++;
            }
            holdIndex = i;
            Debug.WriteLine("holdIndex:"+holdIndex);
        }

        private void MenuItemEdit_Click(object sender, RoutedEventArgs e)
        {
            if (listArticle[holdIndex].Userid != App.MyInfo.id)
            {
                MessageBox.Show("您没有权限编辑该帖子");
                return;
            }
            IsolatedStorageSettings settings = IsolatedStorageSettings.ApplicationSettings;
            settings.Remove("title");
            settings.Remove("content");
            settings.Add("title", listArticle[holdIndex].Title);
            settings.Add("content", listArticle[holdIndex].Content);
            this.NavigationService.Navigate(new Uri("/UpdatePost.xaml?boardname=" + board + "&id=" + listArticle[holdIndex].Id, UriKind.Relative));
        }

        private void MenuItemDelete_Click(object sender, RoutedEventArgs e)
        {
            if (MessageBox.Show("确定删除帖子？", "删除", MessageBoxButton.OKCancel) == MessageBoxResult.Cancel)
                return;
            string url = ByrApi.apiUrl + "/article/" + board + "/delete" +"/"+listArticle[holdIndex].Id+ ByrApi.Encode + ByrApi.appkey;
            HttpUtil.HttpPost(url,Delete_Callback);
        }
        private void Delete_Callback(IAsyncResult asynchronousResult)
        {
            try
            {
                HttpWebRequest hwrq = (HttpWebRequest)asynchronousResult.AsyncState;
                hwrq.BeginGetResponse(DeleteResponse_Callback, hwrq);
            }
            catch (Exception e)
            {
                Debug.WriteLine("POST STRING FAILED:" + e.Message);
            }
        }
        private void DeleteResponse_Callback(IAsyncResult asynchronousResult)
        {
            try
            {
                string result = HttpUtil.ReadToEnd(asynchronousResult);
                XDocument doc = XDocument.Parse(result);
                DebugInfo.writeXml(result);
                foreach (XElement item in doc.Descendants("error").Nodes())
                {
                    if (item.Name == "msg")
                    {
                        this.Dispatcher.BeginInvoke(
                            () =>
                            {
                                MessageBox.Show("删除失败：" + item.Value);
                            }
                            );

                        return;
                    }
                }
                this.Dispatcher.BeginInvoke(
                    () =>
                    {
                        MessageBox.Show("删除成功！");
                        string url = ByrApi.apiUrl + "/threads/" + board + "/" +
                          group_id + ByrApi.Encode + ByrApi.appkey + "page=" + (current_page).ToString();
                        listbox.Items.Clear();
                        Debug.WriteLine(url);
                        HttpUtil.HttpGet(url, HttpWebRequset_Callback);
                        this.progressBarWait.Visibility = Visibility.Visible;
                        
                        this.CloseMeAsPopup();
                    }
                    );



            }
            catch { }

        }

        private void RefreshButton_Click(object sender, EventArgs e)
        {
           GoToPage(current_page);   
        }
        public void GoToPage(int pageNum)
        {
            string url = ByrApi.apiUrl + "/threads/" + board + "/" +
                 group_id + ByrApi.Encode + ByrApi.appkey + "page=" + (pageNum).ToString();
            Debug.WriteLine(url);
            listbox.Items.Clear();
            Debug.WriteLine(url);
            HttpUtil.HttpGet(url, HttpWebRequset_Callback);
            this.progressBarWait.Visibility = Visibility.Visible;
        }

        private void FirstPageButton_Click(object sender, EventArgs e)
        {
            GoToPage(1);
        }

        private void LastPageButton_Click(object sender, EventArgs e)
        {
            GoToPage(total_page);
        }

        private void ShowState(int state)
        {
            if (state == 0)
            {
                BarButtonFirstPageButton.IsEnabled = false;
                BarButtonBackwoard.IsEnabled = false;
                BarButtonForward.IsEnabled = false;
                BarButtonLastPageButton.IsEnabled = false;
                progressBarWait.Visibility = Visibility.Visible;
            }
            else 
            {
                BarButtonFirstPageButton.IsEnabled = true;
                BarButtonBackwoard.IsEnabled = true;
                BarButtonForward.IsEnabled = true;
                BarButtonLastPageButton.IsEnabled = true;
                progressBarWait.Visibility = Visibility.Collapsed;
            }
        }
        private T FindFirstElementInVisualTree<T>(DependencyObject parentElement) where T : DependencyObject
        {
            var count = VisualTreeHelper.GetChildrenCount(parentElement);
            Debug.WriteLine("bbbabababababababab");
            if (count == 0)
                return null;
            for (int i = 0; i < count; i++)
            {
                var child = VisualTreeHelper.GetChild(parentElement, i);
                if (child != null && child is T)
                {
                    return (T)child;
                }
                else
                {
                    var result = FindFirstElementInVisualTree<T>(child);
                    if (result != null)
                        return result;
                }
            }
            return null;
        }



    }
    public class PassValue {
        public ArticleData ArticleItemData { get; set; }
        public PassValue(ArticleData ad)
        {
            this.ArticleItemData = ad;
        }
    }
    public class ArticleData {
        public ArticleData(string username, string imgSource, string content,string id,string title,string userid,List<string> ls,string post_time)
        {
            this.username = username;
            this.ImgSource = imgSource;
            this.Id = id;
            this.Title = title;
            this.Userid = userid;
            this.Content = content;
            this.AttachList = ls;
            this.TimeStamp = post_time;
        }
        public string username {get;set;}
        public string Userid { get; set; }
        public string ImgSource { get; set; }
        public string Content { get; set; }
        public string Id { get; set; }
        public string Title { get; set; }
        public string TimeStamp { get; set; }
        public List<string> AttachList { get; set; }
    }
}